import { defineStore } from 'pinia';
import { store } from '..';
import type { RouteRecordRaw } from 'vue-router';

export interface PermissionState {
  // Permission code list
  permCodeList: string[] | number[];
  // Whether the route has been dynamically added
  isDynamicAddedRoute: boolean;
  // To trigger a menu update
  lastBuildMenuTime: number;
}

export const usePermissionStore = defineStore('app-permission', {
  state: (): PermissionState => ({
    permCodeList: [],
    // Whether the route has been dynamically added
    isDynamicAddedRoute: false,
    // To trigger a menu update
    lastBuildMenuTime: 0,
  }),
  getters: {
    getPermCodeList(): string[] | number[] {
      return this.permCodeList;
    },
    getIsDynamicAddedRoute(): boolean {
      return this.isDynamicAddedRoute;
    },
  },
  actions: {
    setPermCodeList(codeList: string[]) {
      this.permCodeList = codeList;
    },

    setDynamicAddedRoute(added: boolean) {
      this.isDynamicAddedRoute = added;
    },

    resetState(): void {
      this.isDynamicAddedRoute = false;
      this.permCodeList = [];
      this.lastBuildMenuTime = 0;
    },

    async changePermissionCode(codeList: string[]) {
      this.setPermCodeList(codeList);
    },

    // 构建路由
    async buildRoutesAction(): Promise<RouteRecordRaw[]> {
      // 这里我们简化处理，假设所有路径都能访问
      // 在实际项目中，这里需要根据用户角色和权限过滤路由
      return [] as unknown as RouteRecordRaw[];
    },
  },
  persist: true,
});

// Need to be used outside the setup
export function usePermissionStoreWithOut() {
  return usePermissionStore(store);
}
